﻿using System;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using BikeBouncer.Site.Enums;
using Devv.Core.Utils;

namespace BikeBouncer.Site
{
	public partial class Login_aspx : BasePage
	{
		#region Main methods

		protected void Page_Load(Object sender, EventArgs e)
		{
			if (SessionManager.LoginAttempts > 5 || CookieManager.LoginBlockingDate > DateTime.Now.AddMinutes(-30))
			{
				LoginBlockedRedirect();
			}

			RegisterScript(ScriptSource.ColorBox);

			Form.DefaultButton = ButLogin.UniqueID;
			ValTxtUserEmail.ValidationExpression = RegexUtil.Email;

			PanActivated.Visible = false;

			if (!Page.IsPostBack)
			{
				String a = Request.QueryString["a"];

				if (!String.IsNullOrEmpty(a))
				{
					String email = BusinessLayer.Entities.User.ActivationKeyToEmail(a);

					if (email.Contains("@"))
					{
						User user = new User(email);

						if (user.LoginDate < user.RegDate.AddDays(1))
						{
							user.Active = true;
							DataAccess.User_Upsert(user);

							PanActivated.Visible = true;
						}
					}
				}

				ViewState["RedirectUrl"] = Request.QueryString["r"];
			}
			else
			{
				LitLoginInfo.Visible = false;
				LblError.Visible = false;
			}
		}

		#endregion

		#region Login

		protected void ButLogin_Click(Object sender, EventArgs e)
		{
			CheckLogin();
		}

		private void CheckLogin()
		{
			User user = new User(TxtUserEmail.Text);

			if (user.Id > 0)
			{
				if (!user.Active)
				{
					LblError.Text = GetLocalResourceObject("Error_AccountInactive").ToString();
				}
				else if (user.PasswordHash != BusinessLayer.Entities.User.GetPasswordHash(TxtUserEmail.Text, TxtUserPassword.Text))
				{
					LblError.Text = GetLocalResourceObject("Error_InvalidPassword").ToString();
				}
				else
				{
					user.Password = TxtUserPassword.Text;

					SessionManager.LoggedUser = user;
					SessionManager.LoginAttempts = 0;
					CookieManager.LoggedUser = user;
					CookieManager.LoginBlockingDate = DateTime.MinValue;

					Redirect();
				}
			}
			else
			{
				LblError.Text = GetLocalResourceObject("Error_InvalidEmail").ToString();
			}

			if (LblError.Text.Length < 1)
			{
				LitLoginInfo.Visible = true;
			}
			else
			{
				LblError.Visible = true;
			}

            SessionManager.LoginAttempts += 1;
		}

		private void Redirect()
		{
			Object redir = ViewState["RedirectUrl"];
			String url;

			if (redir != null && !String.IsNullOrEmpty(redir.ToString()))
			{
				url = redir.ToString();
			}
			else
			{
				url = "/MyBikes.aspx";
			}

			Response.Redirect(url);
		}

		#endregion
	}
}